<template>
  <dys-table
    :columns="columns"
    :data-source="state.list"
    :loading="state.loading"
    :pagination="false"
    :row-selection="rowSelection"
    row-key="permissionId"
    :custom-row="customRow"
    :hide-tool="!functionId"
    @reload="reload"
  >
    <template #extraLeft v-if="!!functionId">
      <a-button type="primary" @click="handleAdd">
        <PlusCircleOutlined />
        {{ t("新增") }}
      </a-button>
    </template>
    <template #bodyCell="{ column, record }">
      <template
        v-if="editRecord && editRecord.permissionId == record.permissionId"
      >
        <a-form-item v-if="column.dataIndex == 'permissionName'">
          <a-input
            v-model:value="editRecord.permissionName"
            placeholder="请输入权限名称"
            size="small"
            allow-clear
          ></a-input>
        </a-form-item>
        <a-form-item v-if="column.dataIndex == 'permissionCode'">
          <a-input
            v-model:value="editRecord.permissionCode"
            placeholder="请输入权限编码"
            size="small"
            allow-clear
            @change="handleUpperCase"
          ></a-input>
        </a-form-item>
        <template v-if="column.dataIndex == 'operation'">
          <a-button type="link" size="small" @click="handleSave">{{
            t("保存")
          }}</a-button>
          <a-button type="link" size="small" @click="handleCancel">{{
            t("取消")
          }}</a-button>
        </template>
      </template>
      <template v-else>
        <template v-if="column.dataIndex == 'operation'">
          <a-button type="link" size="small" @click="handleEdit(record)">{{
            t("编辑")
          }}</a-button>
          <a-button
            type="link"
            size="small"
            danger
            @click="handleDelete(record)"
          >
            {{ t("删除") }}
          </a-button>
        </template>
      </template>
    </template>
  </dys-table>
</template>
<script lang="ts" setup>
import { cloneDeep } from "lodash";
import { useI18n } from "vue-i18n";
import { reactive, ref, watch } from "vue";
import { useFetchList } from "@/hook/useFetchList";
import { useTableSelect } from "@/hook/useTableSelect";
import { add, del, queryByList, update } from "@/api/system/permission";
import { message } from "ant-design-vue";
import type { TableColumnsType } from "ant-design-vue";
import type {
  PermissionParams,
  QueryResult,
} from "@/api/system/permission/typing";

interface Props {
  /**功能ID */
  functionId: string;
}
const props = defineProps<Props>();
const { t } = useI18n();

const columns = reactive<TableColumnsType>([
  { title: () => t("权限名称"), dataIndex: "permissionName" },
  { title: () => t("权限编码"), dataIndex: "permissionCode" },
  { title: () => t("操作"), dataIndex: "operation", width: 120 },
]);

const params = reactive({
  functionId: props.functionId,
});

const { rowSelection, customRow, clearSelect } = useTableSelect(
  "permissionId",
  {
    multiple: false,
    disabledRow: (record: QueryResult) => !record.permissionId,
  }
);

const { state, reload } = useFetchList(queryByList, {
  params,
  autoFetch: false,
  onLoad: () => (editRecord.value = null),
});

/**默认行 */
const initValue = (): PermissionParams => ({
  permissionId: null,
  permissionCode: null,
  permissionName: null,
  functionId: props.functionId,
});
const editRecord = ref<PermissionParams>();
/**编码转大写 */
const handleUpperCase = () => {
  const upper = editRecord.value.permissionCode.toUpperCase();
  editRecord.value.permissionCode = upper;
};
/**新增行 */
const handleAdd = () => {
  if (editRecord.value) {
    return message.warning("Please save the line being edited first");
  }
  const row = initValue();
  state.list.unshift(row);
  editRecord.value = row;
};
/**编辑行 */
const handleEdit = (record: QueryResult) => {
  if (editRecord.value) {
    return message.warning("Please save the line being edited first");
  }
  editRecord.value = cloneDeep(record);
};
/**保存 */
const handleSave = async () => {
  state.loading = true;
  const { success } = await (editRecord.value.permissionId ? update : add)(
    editRecord.value
  );
  state.loading = false;
  if (success) {
    message.success(t(editRecord.value.permissionId ? "修改成功" : "新增成功"));
    reload();
  }
};
/**删除 */
const handleDelete = async (record: QueryResult) => {
  state.loading = true;
  const { success } = await del({ permissionId: record.permissionId });
  state.loading = false;
  if (success) {
    message.success(t("删除成功"));
    reload();
  }
};
/**取消 */
const handleCancel = () => {
  if (!editRecord.value.permissionId) {
    state.list.shift();
  }
  editRecord.value = null;
};

watch(
  () => props.functionId,
  (id) => {
    if (id) {
      params.functionId = id;
      reload();
    } else {
      state.list = [];
    }
    clearSelect();
  },
  { immediate: true }
);
defineExpose({ rowSelection });
</script>
<style lang="less" scoped>
.ant-form-item {
  margin-bottom: 0;
}
</style>
